package com.sinder.campus_prophet.core.config;

import com.sinder.campus_prophet.core.enums.WebClientProp;
import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.tcp.DefaultSslContextSpec;

import java.util.concurrent.TimeUnit;

/**
 * webClient配置
 * @author v-xyingde
 * @date 2023/3/16/16:21
 */
@Configuration
@ConfigurationPropertiesScan({"com.sinder.campus_prophet.core.enums"})
public class WebClientConfig {
    private final WebClientProp webClientProp;

    public WebClientConfig(WebClientProp webClientProp) {
        this.webClientProp = webClientProp;
    }

    @Bean(name = "wxApiWebClient")
    public WebClient wxApiWebClient() {
        return getWebClient(webClientProp.getWxApi().getWxUrl());
    }


    private WebClient getWebClient(String baseUrl) {
        HttpClient httpClient = HttpClient.create()
                .secure(sslContextSpec -> sslContextSpec.sslContext(DefaultSslContextSpec.forClient()))
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, webClientProp.getWxApi().getConnectTimeoutMillis())
                .doOnConnected(connection -> {
                    connection.addHandlerLast(new ReadTimeoutHandler(webClientProp.getWxApi().getReadTimeoutSeconds(), TimeUnit.SECONDS));
                    connection.addHandlerLast(new WriteTimeoutHandler(webClientProp.getWxApi().getWriteTimeoutSeconds(), TimeUnit.SECONDS));
                });
        return WebClient.builder()
                .baseUrl(baseUrl)
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(webClientProp.getWxApi().getMaxInMemorySize()))
                .build();
    }
}
